package com.learn.demo.email;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 发送带图片的邮件
 *
 * @author banjiawei
 * @date 2021/06/23
 */
@RestController
public class ImgResMailController {
    @Autowired
    private JavaMailSender javaMailSender;
    @Value("${spring.mail.username}")
    private String username;

    @RequestMapping("/imgres/sendImgResMail")
    public void sendImgResMail() throws Exception {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true, "utf-8");
        helper.setSubject("这是一封带图片的测试邮件");
        helper.setFrom(username);
        List<String> stringList = Arrays.asList("2221512643@qq.com", "331939299@qq.com");
        String[] strings = new String[stringList.size()];
        stringList.toArray(strings);
        helper.setTo(strings);
        //helper.setCc("37xxxxx37@qq.com");
        //helper.setBcc("14xxxxx098@qq.com");
        helper.setSentDate(new Date());
        // src='cid:img1' 占位符写法 ，第二个参数true表示这是一个html文本
        helper.setText("<p>这是一封测试邮件，包含两张图片，分别如下</p><p>第一张图片：</p><img src='cid:img1'/><p>第二张图片：</p><img src='cid:img2'/>",true);
        // 第一个参数指的是html中占位符的名字，第二个参数就是文件的位置
        String img1Path = "C:\\Users\\Administrator\\Pictures\\Saved Pictures\\大海.jpg";
        String img2Path = "C:\\Users\\Administrator\\Pictures\\Saved Pictures\\烟花.jpg";
        helper.addInline("img1",new FileSystemResource(new File(img1Path)));
        helper.addInline("img2",new FileSystemResource(new File(img2Path)));
        javaMailSender.send(mimeMessage);
    }
}
